import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 19182
 * Date: 2025-09-27
 * Time: 20:15
 */
public class UdpEchoClient {
    private String serverIp;
    private int serverPort;
    private DatagramSocket socket = null;
    public UdpEchoClient(String Ip, int port) throws SocketException {
        socket = new DatagramSocket();
        serverIp = Ip;
        serverPort = port;
    }
    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        while(true){
            System.out.println("请输入你要发送的内容");

            if(!scanner.hasNext()){
                break;
            }
            String request = scanner.next();
            DatagramPacket reqeustPacket = new DatagramPacket(request.getBytes(),
                    request.getBytes().length,
                    InetAddress.getByName(serverIp), serverPort);
            socket.send(reqeustPacket);
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1", 9090);
        udpEchoClient.start();
    }
}
